package com.ist.word.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.Timer;

import com.ist.word.audio.AudioPlayer;
import com.ist.word.datasoure.SQLiteDataSource;
import com.ist.word.logic.GameConfigurations;
import com.ist.word.logic.WordGameLogic;
import com.ist.word.model.Word;

public class GameMainUI extends JFrame implements ActionListener {

	private JPanel wordMainJPanel;// for refactor word component
	private JPanel lettersButtonJPanel;// for refactor letters component
	private JList wordList;// for word list
	private JScrollPane wordListJScrollPane;
	private JLabel timeBarLabel;// for time bar
	private JLabel scoreBarLabel;// for score bar
	private JLabel lastWordLabel; // last right word or message from application
	private JLabel lastScoreLabel; // last score of right word
	private JLabel WordCountsLabel; //total number of right words user spelled
	private JProgressBar timeJProgressBar;// http://www.iteye.com/topic/293233
											// http://www.linuxidc.com/Linux/2009-12/23645.htm
	//private JProgressBar scoreJProgressBar;// for total scores
	private JTextField resultJTextField;// for user refactored word
	/*for image button http://www.zhouwenze.com/archives/20110414-317.html
	http://www.isstudy.com/java/2002.html*/
	private ImageButton submitImageButton; // for submit
	private ImageButton backspaceImageButton;// for backspace the word
	private ImageButton originalWordImageButton;// for show the original word
	private ImageButton clearImageButton;// for clear the input
	private ImageButton restartImageButton;// for clear the input
	private ImageButton returnToMenuImageButton;// for return back to Menu frame work as pause button
	private ImageButton[] lettersImageButton;
	private Timer gameTimer;
	private int returnToMenuListFlag=0;
	private AudioPlayer buttonAudioPlayer;
	private AudioPlayer CorrectAudioPlayer;
	private AudioPlayer ErrorAudioPlayer;
	
	//set the background image
	final Image backgroundImage = Toolkit.getDefaultToolkit().getImage(
			this.getClass().getResource(GameConfigurations.GAMEMAIN_BACKGROUND));
	private final JComponent backgroundCanvas = new JComponent() {
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			Graphics gg = g.create();
			gg.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
			gg.dispose();
		}
	};
	

	private final int LETTER_NO = 8;
	private int wordCounts=0;//for word counts
	private int totalScore=0;// for total scores
	private char[] letterArray=new char[LETTER_NO];
	private String originalWord="";
	private Vector<String> wordVector=new Vector<String>();
	private DefaultListModel  wordsTransDefaultListModel=new DefaultListModel();
	private WordGameLogic wordGameLogic = new WordGameLogic();
	// frame backgroud http://zhidao.baidu.com/question/276754474.html?an=0&si=1
	// Set initial frame size
	static private final Dimension mainFrameSize = new Dimension(GameConfigurations.GAMEMAIN_FRAMEWIDTH, GameConfigurations.GAMEMAIN_FRAMEHEIGHT);
	
	//control the image size when the frame was resize
	public Dimension getPreferredSize() {
		return mainFrameSize;
	}

	public Dimension getMaximumSize() {
		return mainFrameSize;
	}

	public Dimension getMinimumSize() {
		return mainFrameSize;
	}

	public Dimension getSize() {
		return mainFrameSize;
	}

	//initial the UI component
	public void initUI() {
		// leftWordListsPanel UI
		wordList = new JList(wordsTransDefaultListModel);
		wordList.setSize((int) (300),(int) (50));
		//wordList.setLocation(220, 260);
		//wordList.setBackground(new Color(110,189,255));//如果设置成wordList.setBackground(new Color(110,189,255,30))将无法重绘界面。
		wordList.setForeground(new Color(254,226,100));
		wordList.setFixedCellHeight(20);
		wordList.setFixedCellWidth(180);
		wordList.setOpaque(false);
		wordList.setSelectionForeground(new Color(254,226,100));
		//wordList.setEnabled(false);
		((JLabel)wordList.getCellRenderer()).setOpaque(false);//set the jlist transparent
		wordList.setFont(new Font("Monospaced", Font.BOLD, 14));
		wordList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		wordList.setAutoscrolls(true); 
		//add scroll effect
		wordListJScrollPane = new JScrollPane(wordList); 
		wordListJScrollPane.setLocation(240, 310);
		wordListJScrollPane.setSize(300,200);
		wordListJScrollPane.setBorder(null);
		wordListJScrollPane.setOpaque(false);
		wordListJScrollPane.getViewport().setOpaque(false); 
		
		// rightMainPanel UI
		timeBarLabel = new JLabel("TIME");
		timeBarLabel.setLocation(372, 500);
		timeBarLabel.setFont(new Font("Monospaced", Font.BOLD, 20));
		timeBarLabel.setForeground(new Color(239,229,239));
		timeBarLabel.setSize(60, 20);
		timeJProgressBar = new JProgressBar();
		timeJProgressBar.setLocation(192, 548);
		timeJProgressBar.setSize(415, 20);
		timeJProgressBar.setBackground(new Color(109,170,251,0));
		timeJProgressBar.setForeground(new Color(179,229,10));
		timeJProgressBar.setBorder(null);
		timeJProgressBar.setOpaque(false);
		timeJProgressBar.setMinimum(0);
		timeJProgressBar.setMaximum(101);
		timeJProgressBar.setStringPainted(true);
		timeJProgressBar.setValue(0);

		scoreBarLabel = new JLabel("");
		scoreBarLabel.setFont(new Font("Monospaced", Font.BOLD, 16));
		scoreBarLabel.setForeground(new Color(254,226,100));
		scoreBarLabel.setLocation(495, 10);
		scoreBarLabel.setSize(60, 20);
		/*
		scoreJProgressBar = new JProgressBar();
		scoreJProgressBar.setLocation(300, 50);
		scoreJProgressBar.setSize(200, 20);
		scoreJProgressBar.setBackground(new Color(109,170,251));
		scoreJProgressBar.setForeground(new Color(179,229,10));
		scoreJProgressBar.setMinimum(0);
		scoreJProgressBar.setMaximum(1000);
		scoreJProgressBar.setStringPainted(true);
		scoreJProgressBar.setValue(0);*/
		
		lastWordLabel = new JLabel("LAST WORD：");
		lastWordLabel.setFont(new Font("Monospaced", Font.BOLD, 16));
		lastWordLabel.setForeground(new Color(254,226,100));
		lastWordLabel.setLocation(105, 9);
		lastWordLabel.setSize(250, 20);
		
		WordCountsLabel= new JLabel("NUMBERS：");
		WordCountsLabel.setFont(new Font("Monospaced", Font.BOLD, 16));
		WordCountsLabel.setForeground(new Color(254,226,100));
		WordCountsLabel.setLocation(590, 8);
		WordCountsLabel.setSize(250, 20);
		
		lastScoreLabel = new JLabel("");
		lastScoreLabel.setFont(new Font("Monospaced", Font.BOLD, 18));
		lastScoreLabel.setForeground(new Color(254,226,100));
		lastScoreLabel.setLocation(350, 10);
		lastScoreLabel.setSize(100, 20);
		
		// word buttons

		resultJTextField = new JTextField();
		resultJTextField.setLocation(275, 85);
		resultJTextField.setSize(350, 40);
		resultJTextField.setFont(new Font("Monospaced", Font.BOLD, 36));
		resultJTextField.setBorder(null);
		resultJTextField.setOpaque(false);
		resultJTextField.setForeground(new Color(254,226,100));
		resultJTextField.setBackground(new Color(188,234,250));
		resultJTextField.setEditable(false);
		
		
		submitImageButton = new ImageButton();
		//submitJButton.setToolTipText("SUBMIT");
		submitImageButton.setLocation(250, 230);//setLocation(660, 364);original right corner position
		submitImageButton.setSize(360, 45);//setSize(120, 100) original size
		submitImageButton.addActionListener(this);
		submitImageButton.setImage(GameConfigurations.GAMEMAIN_SUBMIT_NORMALICON);
		submitImageButton.setPressedImage(GameConfigurations.GAME_SUBMIT_HIGHLIGHTICON);
		
		originalWordImageButton = new ImageButton();
		originalWordImageButton.setLocation(703, 300);
		originalWordImageButton.setSize(38, 35);
		originalWordImageButton.addActionListener(this);
		originalWordImageButton.setImage(GameConfigurations.GAMEMAIN_ORIGINALWORD_NORMALICON);
		originalWordImageButton.setPressedImage(GameConfigurations.GAMEMAIN_ORIGINALWORD_HIGNLIGHTICON);
		

		backspaceImageButton = new ImageButton();
		backspaceImageButton.setLocation(662, 355);
		backspaceImageButton.setSize(120, 120);
		backspaceImageButton.addActionListener(this);
		backspaceImageButton.setImage(GameConfigurations.GAMEMAIN_BACKSPACE_NORMALICON);
		backspaceImageButton.setPressedImage(GameConfigurations.GAMEMAIN_BACKSPACE_HIGNLIGHTICON);

		clearImageButton = new ImageButton();
		clearImageButton.setLocation(703, 332);
		clearImageButton.setSize(38, 35);
		clearImageButton.addActionListener(this);
		clearImageButton.setImage(GameConfigurations.GAMEMAIN_CLEAR_NORMALICON);
		clearImageButton.setPressedImage(GameConfigurations.GAMEMAIN_CLEAR_HIGNLIGHTICON);
		
		restartImageButton = new ImageButton();
		restartImageButton.setLocation(663, 455);
		restartImageButton.setSize(120, 120);
		restartImageButton.addActionListener(this);
		restartImageButton.setImage(GameConfigurations.GAMEMAIN_RESTART_NORMALICON);
		restartImageButton.setPressedImage(GameConfigurations.GAMEMAIN_RESTART_HIGHLIGHTICON);
		
		
		returnToMenuImageButton = new ImageButton();
		returnToMenuImageButton.setLocation(0, 310);
		returnToMenuImageButton.setSize(120, 125);
		returnToMenuImageButton.addActionListener(this);
		returnToMenuImageButton.setImage(GameConfigurations.GAMEMAIN_MENU_NORMALICON);
		returnToMenuImageButton.setPressedImage(GameConfigurations.GAMEMAIN_MENU_HIGHLIGHTICON);
		
		
		lettersButtonJPanel = new JPanel(new GridLayout(1, LETTER_NO));
		lettersButtonJPanel.setSize(GameConfigurations.GAMEMAIN_LETTERBUTTON_SIZE*LETTER_NO, GameConfigurations.GAMEMAIN_LETTERBUTTON_SIZE);
		lettersButtonJPanel.setLocation(190, 160);
		lettersButtonJPanel.setOpaque(false);
		lettersImageButton = new ImageButton[LETTER_NO];
		for (int i = 0; i < lettersImageButton.length; i++) {
			lettersImageButton[i] = new ImageButton();
			lettersImageButton[i].setButtonText(letterArray[i]+"");
			lettersImageButton[i].setPressedImage(GameConfigurations.GAMELETTER_PRESS_FOLDER+letterArray[i]+".png");
			lettersImageButton[i].setRolloverImage(GameConfigurations.GAMELETTER_HOVER_FOLDER+letterArray[i]+".png");
			lettersImageButton[i].setImage(GameConfigurations.GAMELETTER_NORMAL_FOLDER+letterArray[i]+".png");
			lettersImageButton[i].setLocation(220 + i * GameConfigurations.GAMEMAIN_LETTERBUTTON_SIZE, 120);
			lettersImageButton[i].setSize(GameConfigurations.GAMEMAIN_LETTERBUTTON_SIZE, GameConfigurations.GAMEMAIN_LETTERBUTTON_SIZE);
			lettersImageButton[i].addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {

					buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
					buttonAudioPlayer.play();
					resultJTextField.setText(resultJTextField.getText()
							+ ((ImageButton) (e.getSource())).getButtonText().toLowerCase());
				}
			});
			lettersButtonJPanel.add(lettersImageButton[i]);
		}
		gameTimer = new Timer(1000, this);

		wordMainJPanel = new JPanel();
		wordMainJPanel.setLayout(null);
		wordMainJPanel.add(wordListJScrollPane);
		wordMainJPanel.add(timeBarLabel);
		wordMainJPanel.add(scoreBarLabel);
		wordMainJPanel.add(WordCountsLabel);
		wordMainJPanel.add(timeJProgressBar);
		//wordMainJPanel.add(scoreJProgressBar);
		wordMainJPanel.add(lastWordLabel);
		wordMainJPanel.add(lastScoreLabel);
		wordMainJPanel.add(resultJTextField);
		wordMainJPanel.add(submitImageButton);
		wordMainJPanel.add(backspaceImageButton);
		wordMainJPanel.add(originalWordImageButton);
		wordMainJPanel.add(clearImageButton);
		wordMainJPanel.add(restartImageButton);
		wordMainJPanel.add(returnToMenuImageButton);
		wordMainJPanel.add(lettersButtonJPanel);

		wordMainJPanel.setOpaque(false);
		// Main frame initial
		this.setTitle("Refactor");
		this.setIconImage(Toolkit.getDefaultToolkit().createImage(this.getClass().getResource(GameConfigurations.GAMETITLE_BARICON)));
		this.setLayout(new BorderLayout());
		this.add(wordMainJPanel, BorderLayout.CENTER);
		this.setSize(mainFrameSize);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.addComponentListener(new ComponentAdapter() {

			@Override
			public void componentResized(ComponentEvent arg0) {
				// TODO Auto-generated method stub
				super.componentResized(arg0);
				repaint();
				repaint(NORMAL, 0, 0, getWidth(), getHeight());
				//System.out.println(123);
			}

		});
	}
	//initial the Variables
	public void intialVariables() {
		Word word=wordGameLogic.getRandomWord();
		originalWord=word.getWords();
		letterArray=wordGameLogic.splitWord(word);
		for (int i = 0; i < lettersImageButton.length; i++) {

			lettersImageButton[i].setButtonText(letterArray[i]+"");
			lettersImageButton[i].setPressedImage(GameConfigurations.GAMELETTER_PRESS_FOLDER+letterArray[i]+".png");
			lettersImageButton[i].setRolloverImage(GameConfigurations.GAMELETTER_HOVER_FOLDER+letterArray[i]+".png");
			lettersImageButton[i].setImage(GameConfigurations.GAMELETTER_NORMAL_FOLDER+letterArray[i]+".png");
		}
		//scoreJProgressBar.setValue(0);
		timeJProgressBar.setValue(0);
		resultJTextField.setText("");
		resultJTextField.grabFocus();
		submitImageButton.setEnabled(true);
		//wordVector.removeAllElements();
		wordsTransDefaultListModel.removeAllElements();
		//System.out.println(wordsTranslationVector.lastElement());
		//Rectangle rect = wordList.getBounds();; 
		//wordList.repaint(rect); 

		//wordList.setListData(wordsTransDefaultListModel);
		//wordList.removeAll();
		wordList.repaint();
		lastWordLabel.setText("LAST WORD: ");
		lastScoreLabel.setText("");
		scoreBarLabel.setText("");
		WordCountsLabel.setText("NUMBERS: ");
		wordCounts=0;
		totalScore=0;
		gameTimer.stop();
		gameTimer.start();
	}

	public GameMainUI() {
		super();

		//initUI();
		//doLay();
//		/intialVariables();
	}
	public  void  resumeGameTimer() {
		gameTimer.restart();
	}

	// set the image background
	public void doLay() {
		Container container = getContentPane();
		container.add(backgroundCanvas);
		container.setSize(getWidth(), getHeight());
		pack();
		setVisible(true);
	}

	public static void main(String[] args) {
//		/new GameSplashScreen().show();
		GameMainUI gameMainUI=new GameMainUI();
		gameMainUI.initUI();
		gameMainUI.doLay();
		gameMainUI.intialVariables();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if (clearImageButton == e.getSource()) {

			buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
			buttonAudioPlayer.play();
			//System.out.println("clear");
			resultJTextField.setText("");
		}
		if (originalWordImageButton == e.getSource()) {

			buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
			buttonAudioPlayer.play();
			
			resultJTextField.setText(originalWord);
			submitImageButton.setEnabled(false);
		}
		if (backspaceImageButton == e.getSource()) {

			buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
			buttonAudioPlayer.play();
			//System.out.println("backspace");
			// 判断
			if (resultJTextField.getText().length() > 0) {
				resultJTextField.setText(resultJTextField.getText().substring(
						0, resultJTextField.getText().length() - 1));
			}
		}
		if (submitImageButton == e.getSource()) {

			buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
			buttonAudioPlayer.play();
			//System.out.println("submit");
			//int value = scoreJProgressBar.getValue();
			//timeJProgressBar.setValue(new WordGameLogic().scoreStatistics(word)+value);
			Word word=new Word();
			word.setWords(resultJTextField.getText());
			//System.out.println(wordVector.contains(word.getWords()));
			if (null!=wordGameLogic.getWord(word)&&!wordVector.contains(word.getWords())&& word.getWords().length()>=3) {

				CorrectAudioPlayer=new AudioPlayer(GameConfigurations.GAMEMAIN_CORRECT);
				CorrectAudioPlayer.play();
				
				word=wordGameLogic.getWord(word);
				wordCounts++;
				totalScore=totalScore+wordGameLogic.scoreStatistics(word);
				scoreBarLabel.setText(""+totalScore);
				wordVector.add(word.getWords());
				wordsTransDefaultListModel.addElement(new String(word.getWords()+" - "+word.getTranslation()));
				//wordList.setListData(wordsTranslationVector);
				//System.out.println(word.getWords()+" - "+word.getTranslation());
				lastWordLabel.setText("LAST WORD: "+word.getWords());
				lastScoreLabel.setText(""+wordGameLogic.getWordScore(word));
				WordCountsLabel.setText("NUMBERS: "+wordCounts);
			}else {
				ErrorAudioPlayer=new AudioPlayer(GameConfigurations.GAMEMAIN_ERROR);
				ErrorAudioPlayer.play();
			}
			
			resultJTextField.setText("");
		}
		if (restartImageButton == e.getSource()) {
			//System.out.println("restart");
			//wordsTransDefaultListModel.removeAllElements();

			buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
			buttonAudioPlayer.play();
			intialVariables();

			restartImageButton.repaint();
			
		}
		if (returnToMenuImageButton == e.getSource()) {
			returnToMenuListFlag=1;
			buttonAudioPlayer=new AudioPlayer(GameConfigurations.GAMEBUTTON_MUSIC);
			buttonAudioPlayer.play();
			gameTimer.stop();
			returnToMenuImageButton.setBackground(new Color(255, 255, 255,0));

			
		}
		if (gameTimer == e.getSource()) {
			int value = timeJProgressBar.getValue();
			if (value <= 100)
				timeJProgressBar.setValue(++value);
			else {
				submitImageButton.setEnabled(false);
				resultJTextField.setText(originalWord);
				gameTimer.stop();
			}

		}

	}// 实现按钮事件
	/*
	 * Logic logic; Word word; JButtons //字母按钮 JText //拼词结果 listener事件函数
	 * 窗体：JFrame 面板：JPanel 按钮、字母：JButton 说明文字：JLabel Time：JProgressBar
	 * 分数：JTextPane
	 * 
	 * 其他：提示框，气泡提示，程序图标，托盘图标等等
	 * 
	 * }
	 */

	public int getReturnToMenuListFlag() {
		return returnToMenuListFlag;
	}

	public void setReturnToMenuListFlag(int returnToMenuListFlag) {
		this.returnToMenuListFlag = returnToMenuListFlag;
	}
}
